package com.base.core.error;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public abstract class ErrorUtils {

    private static final Logger log = LoggerFactory.getLogger(ErrorUtils.class);

    public static GenericException wrap(Throwable cause) {
        if (cause instanceof GenericException) {
            return (GenericException) cause;
        }
        return log(new GenericException(GenericError.UNKNOWN, cause));
    }

    public static GenericException wrap(EnumWithText error) {
        return log(new GenericException(error));
    }

    public static GenericException wrap(EnumWithText error, Throwable cause) {
        return log(new GenericException(error, cause));
    }

    public static GenericException wrap(EnumWithText error, String message) {
        return log(new GenericException(error, message));
    }

    public static GenericException wrap(EnumWithText error, String message, Throwable cause) {
        return log(new GenericException(error, message, cause));
    }

    public static StringWriter getPrintStract(Throwable e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            //将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw;
    }

    /**
     * Print the dealt exception.
     * @param e
     * @return
     */
    private static GenericException log(GenericException e) {
        if (e.getCause() == null) {
            log.error("Code:" + e.getError().toString() + ", text:" + e.getError().text() + ", message:"
                    + e.getMessage());
        } else {
            log.error("Code:" + e.getError().toString() + ", text:" + e.getError().text() + ", message:"
                    + e.getMessage(), e.getCause());
        }
        return e;
    }
}
